import pickle
import base64

from django_redis import get_redis_connection



def merge_cart_cookie_to_redis(request, response, user):
    # 读取cookie信息
    cookie_cart = request.COOKIES.get('cart')
    print('cookie-cart', cookie_cart)
    if cookie_cart is not None:
        cookie_cart = pickle.loads(base64.b64decode(cookie_cart.encode()))
        #cart{sku_id:{count: count, selected: true}, sku_id: {}}

        # 读取redis信息
        redis_conn = get_redis_connection('cart')
        redis_cart = redis_conn.hgetall('cart_%s' % user.id)
        redis_cart_slected = redis_conn.smembers('cart_selected_%s' % user.id)
        cart = {}
        for sku_id, count in redis_cart.items():
            cart[int(sku_id)] = int(count)

        # 把cookie信息添加到redis中
        for sku_id, sku_dict in cookie_cart.items():
            # 购物车合并数量这里用的是数量替换,防止库存不足
            cart[sku_id] = sku_dict['count']
            if sku_dict['selected']:
                redis_cart_slected.add(sku_id)
        if cart:
            pl = redis_conn.pipeline()
            pl.hmset('cart_%s' % user.id, cart)
            pl.sadd('cart_selected_%s' % user.id, *redis_cart_slected)
            pl.execute()

        #删除cookie中的信息
        response.delete_cookie('cart')
    # else:
    #     return response

    return response